#!/bin/bash
#检测是否可以上外网
#nginx需要的常用软件包
yum_pack="gcc  curl vim iotop  make rsync lrzsz tree ntpdate  pcre pcre-devel zlib zlib-devel openssl openssl-devel"
OS=`cat /etc/redhat-release|sed -r 's/.* ([0-9]+)\..*/\1/'`
check_network(){
	echo "检查网络是否可以访问外网,不能访问外网将停止脚本运行"
	check_net=`curl -I -m 10 -o /dev/null -s -w %{http_code} www.baidu.com`
	if [ ${check_net} -ne 200 ];then
            echo "请检查网络是否正常，能否访问外网"
	    exit 1
	fi
}

#安装wegt用于替换阿里源
install_wget(){
	yum install -y wget
}

#替换阿里源
change_aliyuan(){
	echo "--------------------------------修改镜像源为阿里镜像源------------------------------------"
	if [ "$OS" == "7" ];then
		echo "Begin install YUM Repo ....."
		cd /etc/yum.repos.d/ && tar zcvf /opt/yum.bak.tar.gz /etc/yum.repos.d/* && rm -rf /etc/yum.repos.d/*
		curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
		wait
		yum repolist
		echo " End install YUM Repo ...."
		wait
	
	else
		
		echo "Begin install YUM Repo ....."
		cd /etc/yum.repos.d/ && tar -zcvf /opt/yum.bak.tar.gz /etc/yum.repos.d/* && rm -rf /etc/yum.repos.d/
		curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
		wait
		yum repolist
		echo " End install YUM Repo ...."
		wait
	fi
}

#下载常用的软件包
yum_install_packges(){
	echo "yum安装nginx需要的软件"
	yum  install -y -q ${yum_pack} > /dev/null 2>&1
}

#下载nginx1.16.1版本的软件包
download_nginx(){
	wget -P /usr/local/src http://nginx.org/download/nginx-1.16.1.tar.gz
}

install_nginx(){
	cd /usr/local/src/ && tar xvfz nginx-1.16.1.tar.gz
	cd nginx-1.16.1
	./configure  --prefix=/usr/local/nginx \
        --sbin-path=/usr/local/nginx/sbin/nginx \
        --with-http_stub_status_module \
        --with-http_ssl_module \
        --with-http_realip_module
        wait
	make && make install  > /dev/null 2>&1
}

backup_nginxconf(){
	mv /usr/local/nginx/conf/nginx.conf  /usr/local/nginx/conf/nginx.conf.bak
        cp /home/nginx.conf.template /usr/local/nginx/conf/nginx.conf
}

#启动nginx
start_nginx(){
	/usr/local/nginx/sbin/nginx 
	WebPort=`netstat -nlt |grep 8000|awk '{print $4}'| cut -d : -f 2`
	if [ "$WebPort" = "8000" ];then 
		echo "Nginx service has started"
	else
		echo "Please start nginx manually, starting up as: cd /usr/local/nginx/sbin && ./nginx "
	fi
}

main(){
	check_network;
	install_wget;
	change_aliyuan;
	yum_install_packges;
#	download_nginx;
	install_nginx;
        backup_nginxconf;
	start_nginx;
}
main
	
